﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using YF_Music.Core.Caches;
using YF_Music.Core.Models;

namespace YF_Music.Core.Services
{
  /// <summary>
  /// 读取/加载音乐列表的会话类 并执行自动保存
  /// </summary>
  public class PlaylistSession : IDisposable
  {
    private readonly string playlistName;
    private readonly List<MusicItem> items;
    private readonly PeriodicTimer timer;
    private readonly CancellationTokenSource cts = new();
    private bool isDirty = false;

    public IReadOnlyList<MusicItem> Items => items;

    public PlaylistSession(string name, string loadPath)
    {
      playlistName = name;
      items = LoadOrInit(loadPath);
      timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
      _ = StartAutoSaveAsync(); // 开始后台任务
    }

    private async Task StartAutoSaveAsync()
    {
      try
      {
        while (await timer.WaitForNextTickAsync(cts.Token))
        {
          TrySave();
        }
      }
      catch (OperationCanceledException)
      {
        // 正常结束
      }
    }

    public void Add(MusicItem item)
    {
      items.Add(item);
      isDirty = true;
    }

    public void Remove(MusicItem item)
    {
      items.Remove(item);
      isDirty = true;
    }

    public void MarkDirty() => isDirty = true;

    public void TrySave()
    {
      if (!isDirty) return;
      PlaylistManager.SavePlaylist(playlistName, items);
      isDirty = false;
    }

    public void ForceSave()
    {
      PlaylistManager.SavePlaylist(playlistName, items);
      isDirty = false;
    }

    public void Dispose()
    {
      cts.Cancel();
      ForceSave();
      cts.Dispose();
      timer.Dispose();
    }

    private List<MusicItem> LoadOrInit(string path)
    {
      var loaded = PlaylistManager.LoadPlaylist(playlistName);
      if (loaded != null && loaded.Count > 0)
        return loaded;

      var files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly)
     .Where(f => f.EndsWith(".mp3") || f.EndsWith(".wav") || f.EndsWith(".flac"));
      var list = files.Select(MusicItem.FromFile).ToList();
      if (list.Count > 0)
        PlaylistManager.SavePlaylist(playlistName, list);

      return list;
    }
  }

}
